package com.okaixz.client.service.impl;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.okaixz.client.model.domain.PwdInfo;
import com.okaixz.client.mapper.PwdInfoMapper;
import com.okaixz.client.model.domain.PwdTagInfo;
import com.okaixz.client.model.domain.User;
import com.okaixz.client.model.dto.PwdSaveAllParams;
import com.okaixz.client.service.IPwdInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.okaixz.client.service.IPwdTagInfoService;
import com.okaixz.client.service.IUserService;
import com.okaixz.common.client.exception.BusinessException;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.manager.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdz
 * @since 2025-09-17
 */
@Service
@Slf4j
public class PwdInfoServiceImpl extends ServiceImpl<PwdInfoMapper, PwdInfo> implements IPwdInfoService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPwdTagInfoService pwdTagInfoService;



    @Override
    public PwdInfo addPwdInfo(PwdInfo pwdInfo) {
        User user = userService.getTokenUser();
        pwdInfo.setUserId(user.getUserId());
        pwdInfo.setModifyTime(LocalDateTime.now());

        boolean b = saveOrUpdate(pwdInfo);
        if(b){
            return pwdInfo;
        }
        return null;
    }

    @Override
    public List<PwdInfo> uploadAll(List<PwdInfo> pwdInfoList) {
        User user = userService.getTokenUser();
        for (PwdInfo pwdInfo : pwdInfoList) {
            pwdInfo.setUserId(user.getUserId());
        }
        boolean b = saveOrUpdateBatch(pwdInfoList);
        if (b) {
            return pwdInfoList;
        }
        return null;
    }

    @Override
    public PwdSaveAllParams downloadAll() {
        String userId = BaseContext.getUserId();
        if (userId == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
//        List<PwdTagInfo> tagInfoList = pwdTagInfoService.downloadAll();
        List<PwdInfo> pwdInfoList = lambdaQuery().eq(PwdInfo::getUserId, userId)
                .list();

        PwdSaveAllParams saveAllParams = new PwdSaveAllParams();
        saveAllParams.setPwdInfoList(pwdInfoList);
//        saveAllParams.setPwdTagInfoList(tagInfoList);

        return saveAllParams;
    }
    @Override
    public boolean saveOrUpdateBatch(Collection<PwdInfo> entityList) {
        int batchSize = 1000;
        Assert.notEmpty(entityList, "error: entityList must not be empty");
        Class<?> cls = currentModelClass();
        TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
        Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
        String keyProperty = tableInfo.getKeyProperty();
        Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
        try (SqlSession batchSqlSession = sqlSessionBatch()) {
            int i = 0;
            PwdInfo oldPwdInfo = null;
            for (PwdInfo entity : entityList) {
                Long id = entity.getId();
                oldPwdInfo=null;
                if (id != null) {
                    oldPwdInfo=getById(id);
                }
                if (oldPwdInfo==null||!oldPwdInfo.getUserId().equals(entity.getUserId())) {
                    //未查询到信息或用户不一致都执行插入
                    entity.setId(null);
                    batchSqlSession.insert(sqlStatement(SqlMethod.INSERT_ONE), entity);
                } else {
                    MapperMethod.ParamMap<PwdInfo> param = new MapperMethod.ParamMap<>();
                    param.put(Constants.ENTITY, entity);
                    batchSqlSession.update(sqlStatement(SqlMethod.UPDATE_BY_ID), param);
                }
                // 不知道以后会不会有人说更新失败了还要执行插入 😂😂😂
                if (i >= 1 && i % batchSize == 0) {
                    batchSqlSession.flushStatements();
                }
                i++;
            }
            batchSqlSession.flushStatements();
        }
        return true;
    }

    @Override
    public Boolean deleteAll(List<Long> ids) {
        User user = userService.getTokenUser();
        boolean b = lambdaUpdate().eq(PwdInfo::getUserId, user.getUserId())
                .in(PwdInfo::getId, ids)
                .remove();
        return b;
    }

    @Override
    public boolean deleteTag(PwdTagInfo pwdTagInfo) {
        User user = userService.getTokenUser();
        List<PwdInfo> list = lambdaQuery().eq(PwdInfo::getUserId, user.getUserId())
                .eq(PwdInfo::getTagName, pwdTagInfo.getName())
                .eq(PwdInfo::getType, pwdTagInfo.getType())
                .list();
//        log.info("11111111111======================list:{}", list);
        if (list == null||list.size()==0) {
            return true;
        }
        for (PwdInfo pwdInfo : list) {
            pwdInfo.setTagName(null);
        }
//        log.info("======================list:{}", list);
        boolean result=super.saveOrUpdateBatch(list);
        return result;
    }


}
